/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.ads.service.ks.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.dev2.api.sdk.adgroupfeed.api.AdgroupFeedService;
import com.baidu.dev2.api.sdk.adgroupfeed.model.*;
import com.baidu.dev2.api.sdk.common.ApiErrorInfo;
import com.baidu.dev2.api.sdk.common.ApiRequestHeader;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.sdk.client.DyKsClient;
import com.dy.sdk.client.DyTtClient;
import com.dy.sdk.model.request.ks.KsUpdateBidRequest;
import com.dy.sdk.model.request.ks.KsUpdateDayBudgetRequest;
import com.dy.sdk.model.request.ks.KsUpdateStatusRequest;
import com.dy.sdk.model.request.tt.TtUpdateStatusRequest;
import com.dy.sdk.model.response.ks.KsResponse;
import com.dy.sdk.utils.DyConstant;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.gdt.service.GdtAdvFundsService;
import com.pig4cloud.pig.ads.gdt.service.IGdtAdgroupService;
import com.pig4cloud.pig.ads.pig.mapper.AdPlanMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdPromotionMapper;
import com.pig4cloud.pig.ads.pig.mapper.PlatformJobInfoMapper;
import com.pig4cloud.pig.ads.pig.mapper.bd.BdAdgroupMapper;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAdgroupMapper;
import com.pig4cloud.pig.ads.pig.mapper.ks.KsUnitMapper;
import com.pig4cloud.pig.ads.service.AdvertiserService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.service.TtPlanCostWarningService;
import com.pig4cloud.pig.ads.service.ks.KsAccesstokenService;
import com.pig4cloud.pig.ads.service.ks.KsUnitService;
import com.pig4cloud.pig.ads.utils.CronUtils;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.*;
import com.pig4cloud.pig.api.entity.bd.BdAdgroup;
import com.pig4cloud.pig.api.entity.ks.KsPlanReq;
import com.pig4cloud.pig.api.entity.ks.KsUnit;
import com.pig4cloud.pig.api.enums.AdPlanEnum;
import com.pig4cloud.pig.api.enums.StatusEnum;
import com.pig4cloud.pig.api.gdt.dto.GdtAdgroupDto;
import com.pig4cloud.pig.api.gdt.entity.GdtAdgroup;
import com.pig4cloud.pig.api.gdt.entity.GdtAdvFunds;
import com.pig4cloud.pig.api.gdt.vo.GdtAdvFundsVO;
import com.pig4cloud.pig.api.util.Constants;
import com.pig4cloud.pig.api.util.MapUtils;
import com.pig4cloud.pig.api.vo.AdvertisingWarningVO;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.DateUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 快手广告组信息表
 *
 * @author yuwenfeng
 * @date 2022-03-26 17:31:08
 */
@Service("KsUnitService")
@RequiredArgsConstructor
public class KsUnitServiceImpl extends ServiceImpl<KsUnitMapper, KsUnit> implements KsUnitService {

	private final KsAccesstokenService ksAccesstokenService;

	private final AdvertiserService advertiserService;

	@Autowired
	private BdAdgroupMapper bdAdgroupMapper;

	@Autowired
	private TtAccesstokenService ttAccesstokenService;

	@Autowired
	private IGdtAdgroupService gdtAdgroupService;

	private final GdtAdvFundsService gdtAdvFundsService;

	private final StringRedisTemplate stringRedisTemplate;

	private final PlatformJobInfoMapper platformJobInfoMapper;

	private final AdPlanMapper adPlanMapper;

	private final AdPromotionMapper adPromotionMapper;

	@Resource
	private GdtAccesstokenService gdtAccesstokenService;

	@Resource
	private GdtAdgroupMapper gdtAdgroupMapper;

	private final TtPlanCostWarningService ttPlanCostWarningService;

	//头条请求修改状态地址
	@Value("${ad_third_url}")
	private String adThirdUrl;

	//头条请求修改状态地址
	@Value("${ad_update_plan_status_url}")
	private String updatePlanStatusUrl;

	@Value(value = "${gdt_url}")
	private String gdtUrl;

	@Value(value = "${gdt_group_update_url}")
	private String gdtGroupUpdateUrl;

	/**
	 * 广告计划修改状态
	 * @param req
	 * @return
	 */
	@Override
	public R updateStatus(KsPlanReq req) {
		//媒体类型 1.头条,8.广点通,10快手
		Integer mediaType = req.getMediaType();
		try {
			//头条
			if (1 == mediaType) {
				R result = updateTTStatus(req);
				if (result.getCode() == 0) {
					if ("Y".equals(req.getIgnoreWarning())) {
						stringRedisTemplate.opsForValue().set(Constants.TT_REDIS_ADID_COST_WARNING_KEY_PRIX_ + req.getUnitId(), "N");
						AdvertisingWarningVO vo = new AdvertisingWarningVO();
						vo.setAdvertiserId(String.valueOf(req.getAdvertiserId()));
						vo.setPlanCostWarning(null);
						return this.submitWarning(vo);
					}
					return result;
				} else {
					return result;
				}
			} else if (8 == mediaType) {//广点通
				R result = updateGDTStatus(req);
				if (result.getCode() == 0) {
					if ("Y".equals(req.getIgnoreWarning())) {
						GdtAdgroup gdtAdgroup = gdtAdgroupService.getBaseMapper().selectById(req.getUnitId());
						if (gdtAdgroup == null) {
							return R.failed("参数错误");
						}

						stringRedisTemplate.opsForValue().set(Constants.GDT_REDIS_ADGROUP_COST_WARNING_KEY_PRIX_ + req.getUnitId(), "N");
						GdtAdvFundsVO vo = new GdtAdvFundsVO();
						vo.setAccountId(gdtAdgroup.getAccountId());
						vo.setGroupCostWarning(null);
						return this.submitWarning(vo);
					}
					return result;
				} else {
					return result;
				}
			} else if (10 == mediaType) {//快手
				return updateKSStatus(req);
			} else if (9 == mediaType) {
				return updateBdStatus(req);
			} else {
				return R.failed("媒体类型传入错误,没找到对应的媒体类型");
			}
		} catch (Exception e) {
			log.error("更新状态失败:", e);
			return R.failed("更新状态失败，请稍后重试");
		}
	}

	/**
	 * 广告计划修改预算
	 * @param req
	 * @return
	 */
	@Override
	public R updateDayBudget(KsPlanReq req) {
		try {
			AccountToken ksAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.KS.getValue(),req.getAdvertiserId().toString());
			if (Objects.isNull(ksAccountToken)) {
				return R.failed("此广告账户Token已失效");
			}
			DyKsClient ksClient = new DyKsClient("");
			KsUnit ksUnit = baseMapper.selectKsUnitList(req.getUnitId().toString());
			if (Objects.isNull(ksUnit)) {
				return R.failed("当前广告计划不存在 !");
			}
			BigDecimal budget = req.getBudget();
			//广告组单日预算金额，单位：厘，指定 0 表示预算不限，默认为 0；不小于 100 元，不超过 100000000 元，仅支持输入数字;
			Boolean flag = budget.compareTo(new BigDecimal(100)) == -1 || budget.compareTo(new BigDecimal(100000000)) == 1;
			if(0 == budget.intValue()){
				flag=false;
			}
			if (flag) {
				return R.failed("修改预算值范围要在:不小于 100 元，不超过 100000000 元");
			}
			//将预算值由单位元转换成单位厘
			Long budgetLong = budget.multiply(new BigDecimal("1000")).longValue();

			//1 修改日预算  2 定时修改日预算
			if (StatusEnum.TYPE_ONE.getStatus().equals(req.getType())) {
				//获得调用ks修改预算接口的对象
				KsUpdateDayBudgetRequest updateDayBudgetRequest = new KsUpdateDayBudgetRequest();
				updateDayBudgetRequest.setAdvertiser_id(req.getAdvertiserId());
				updateDayBudgetRequest.setUnit_id(req.getUnitId());
				//单位要转为厘
				updateDayBudgetRequest.setDay_budget(budgetLong);
				String result = ksClient.call4Post(updateDayBudgetRequest, ksAccountToken.getAccessToken());
				KsResponse response = JSON.parseObject(result, KsResponse.class);
				if ("0".equals(response.getCode())) {
					KsUnit updateKsUnit = new KsUnit();
					updateKsUnit.setUnitId(req.getUnitId());
					//存入mysql表:ks_unit,单位为元
					updateKsUnit.setDayBudget(budget.longValue());
					//修改数据表:ks_unit的出价信息
					this.baseMapper.update(updateKsUnit);
					return R.ok(response.getMessage(), ">>>>>>快手修改广告计划预算成功");
				} else {
					log.error(">>>>>>快手修改广告计划预算异常：" + result);
					return R.failed(response.getMessage());
				}
			} else {
				Long unitId = req.getUnitId();
				String jobName = "修改快手广告计划预算";
				Integer operate = StatusEnum.OPERATE_TYPE_SIX.getStatus();
				try {
					//第二天凌晨执行
					Date exeTime = DateUtil.timeToBeginDay(DateUtil.getDate(new Date(), 1));
					String cronDate = CronUtils.getCron(exeTime);
					String exeParam = JSONObject.toJSONString(req);
					List<PlatformJobInfo> platformJobInfoList = platformJobInfoMapper.selectList(Wrappers.<PlatformJobInfo>query().lambda().eq(PlatformJobInfo::getUniqueId, unitId).eq(PlatformJobInfo::getOperateType, operate).eq(PlatformJobInfo::getType, StatusEnum.AD_TYPE_THREE.getStatus()).gt(PlatformJobInfo::getExecuteTime, new Date()));
					if (CollectionUtils.isEmpty(platformJobInfoList)) {
						//新增  -- 已经执行的以新增为标准，未执行以修改为准
						platformJobInfoMapper.insert(new PlatformJobInfo(unitId, jobName, cronDate, exeTime, exeParam, StatusEnum.JOB_STATUS_ONE.getStatus(), operate, StatusEnum.AD_TYPE_THREE.getStatus()));
					} else {
						//修改账号修改任务-----如果还没有执行
						platformJobInfoMapper.updateById(new PlatformJobInfo(unitId, exeParam, cronDate, exeTime, StatusEnum.JOB_STATUS_ONE.getStatus(), platformJobInfoList.get(0).getId()));
					}
				} catch (Exception e) {
					log.error("budgetUpdate  cron  is error:", e);
					return R.failed("定时修改快手日预算异常，请稍后重试");

				}
				return R.ok();
			}

		} catch (Exception e) {
			log.error("budgetUpdate is error", e);
			return R.failed("修改预算异常" + e.getMessage());
		}
	}

	/**
	 * 广告计划修改出价
	 * @param req
	 * @return
	 */
	@Override
	public R updateBid(KsPlanReq req) {
		try {
			AccountToken ksAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.KS.getValue(),req.getAdvertiserId().toString());
			if (Objects.isNull(ksAccountToken)) {
				return R.failed("此广告账户Token已失效");
			}
			DyKsClient ksClient = new DyKsClient("");
			KsUnit ksUnit = baseMapper.selectKsUnitList(req.getUnitId().toString());
			if (Objects.isNull(ksUnit)) {
				return R.failed("当前广告计划不存在 !");
			}
			//bidType:出价类型(1：CPM，2：CPC，6：OCPC(使用 OCPC 代表 OCPX)，10：OCPM，20：eCPC)
			Integer bidType = ksUnit.getBidType();

			//广告组 bid_type 为 CPC 和 eCPC 时：不得低于 0.2 元，不得高于 100 元，单位：厘；广告组 bid_type 为 OCPC 时：行为出价不得低于 1 元；激活出价不得低于 5 元（白名单用户不得低于 2 元），单位：厘
			if (Objects.nonNull(bidType)) {
				Boolean flag = false;
				if (bidType == 2 || bidType == 20) {
					flag = req.getCpaBid().compareTo(new BigDecimal("0.2")) == -1 || req.getCpaBid().compareTo(new BigDecimal(100)) == 1;
				}
				if (flag) {
					return R.failed("pricing为CPC和eCPC时取值范围：0.2-100元");
				}
			}
			//将出价由元转换为厘
			long[] unitIds = new long[]{req.getUnitId()};
			BigDecimal cpaBid = req.getCpaBid();
			Long cpaBidLong = cpaBid.multiply(new BigDecimal("1000")).longValue();
			//获得调用ks修改出价接口的对象
			KsUpdateBidRequest updateBidRequest = new KsUpdateBidRequest();
			updateBidRequest.setAdvertiser_id(req.getAdvertiserId());
			updateBidRequest.setUnit_id(req.getUnitId());
			updateBidRequest.setUnit_ids(unitIds);
			//单位要转为厘
			updateBidRequest.setBid(cpaBidLong);
			//调用快手修改出价的接口
			String result = ksClient.call4Post(updateBidRequest, ksAccountToken.getAccessToken());
			KsResponse response = JSON.parseObject(result, KsResponse.class);
			if (StringUtils.equals(response.getCode(), "0")) {
				KsUnit updateKsUnit = new KsUnit();
				updateKsUnit.setUnitId(req.getUnitId());
				//存入mysql表:ks_unit,单位为元
				updateKsUnit.setCpaBid(cpaBid.longValue());
				//修改数据表:ks_unit的出价信息
				this.baseMapper.update(updateKsUnit);
				return R.ok(response.getMessage(), ">>>>>>快手修改广告计划出价成功");
			} else {
				log.error(">>>>>>快手修改广告计划出价异常：" + result);
				return R.failed(response.getMessage());
			}
		} catch (Exception e) {
			log.error(">>>>>>快手修改广告计划出价异常：" + e.getMessage());
			e.printStackTrace();
			return R.failed(">>>>>>快手修改广告计划出价异常");
		}
	}

	@Override
	public R getPutStatus(Set<Long> adIdSet) {
		List<KsUnit> list = baseMapper.selectList(Wrappers.<KsUnit>lambdaQuery().select(KsUnit::getUnitId, KsUnit::getPutStatus).in(KsUnit::getUnitId, adIdSet));
		return R.ok(list);
	}

	/**
	 * 修改头条状态
	 * @param req
	 * @return
	 */
	private R updateTTStatus(KsPlanReq req){
		//广告账号id
		Long advertiserId = req.getAdvertiserId();
		//广告账号id
		Long unitId = req.getUnitId();
		//当前状态
		String optStatus = req.getOptStatus().toString();
		//获得当前的状态信息
		String allStatus = getStatus(req, optStatus);
		try{
			//等出对应的状态存在表中的数据
			String status = null;
			if (StringUtils.equals(allStatus, "enable")){
				status = "AD_STATUS_ENABLE";
			} else if( StringUtils.equals(allStatus, "ENABLE")) {
				status = "ENABLE";
			} else if (StringUtils.equals(allStatus, "disable")){
				status = "AD_STATUS_DISABLE";
			} else if ( StringUtils.equals(allStatus, "DISABLE")) {
				status = "DISABLE";
			}

			//判断当前表中状态是和数据库中一致
			if (req.getVersionType().equals("2")){
				AdPromotion adPromotion = adPromotionMapper.selectByPromotionId(unitId);
				if (Objects.isNull(adPromotion)) {
					return R.failed("无此体验版头条广告计划");
				}
				if(StringUtils.equals(status,adPromotion.getStatus())){
					return R.failed("当前传入状态错误");
				}
			}else {
				AdPlan adPlan = adPlanMapper.selectById(unitId);
				if (Objects.isNull(adPlan)) {
					return R.failed("无此头条广告计划");
				}
				if(StringUtils.equals(status,adPlan.getStatus())){
					return R.failed("当前传入状态错误");
				}
			}
			DyTtClient ttClient = new DyTtClient(DyConstant.TT_DEFAULT_ENDPOINT_EXPERIENCE);

			String token = ttAccesstokenService.fetchAccesstoken(advertiserId.toString());
			if (StringUtils.isBlank(token)) {
				return R.failed("当前账号token失效");
			}
			String resultStr;
			if(req.getVersionType().equals("2")) {
				//新广告计划状态修改
				log.warn("新广告计划状态修改");
				List<Map<String, Object>> paramList = new ArrayList<>();
				Map<String, Object> optStatusMap = new HashMap<String, Object>();
				optStatusMap.put("promotion_id", unitId);
				optStatusMap.put("opt_status", allStatus);
				paramList.add(optStatusMap);
				TtUpdateStatusRequest ttUpdateStatusRequest=new TtUpdateStatusRequest();
				ttUpdateStatusRequest.setAdvertiser_id(advertiserId);
				ttUpdateStatusRequest.setData(paramList);
				log.warn("ttUpdateStatusRequest"+ttUpdateStatusRequest.toString());
				resultStr = ttClient.call4Post(ttUpdateStatusRequest,token);
			}else {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("advertiser_id", advertiserId);
				String url = null;
				//广告计划状态修改
				Long[] adIds = {unitId};
				param.put("ad_ids", adIds);
				param.put("opt_status", allStatus);
				url = updatePlanStatusUrl;
				resultStr = OEHttpUtils.doPost(adThirdUrl + url, param, token);
			}
			log.warn("updateThirdData response:" + resultStr);
			JSONObject obj = JSON.parseObject(resultStr);
			String code =obj.getString("code");
			if (StringUtils.equals(code, "0")) {
				if(req.getVersionType().equals("2")){
					adPromotionMapper.updateByPrimaryKeySelective(new AdPromotion(unitId,status));
				}else {
					adPlanMapper.updateById(new AdPlan(unitId, status));
				}
				return R.ok(obj.getString("data"),"头条开关修改成功");
			}else {
				return R.failed("头条开关修改失败:" + obj.get("message"));
			}
		}catch (Exception e){
			e.printStackTrace();
			return R.failed("头条开关修改异常，请稍后重试");
		}
	}

	/**
	 * 修改广点通状态
	 * @param req
	 * @return
	 */
	private R updateGDTStatus(KsPlanReq req) {

		//广告账号id
		Long advertiserId = req.getAdvertiserId();
		//广告账号id
		Long unitId = req.getUnitId();
		//当前状态
		String optStatus = req.getOptStatus().toString();
		//获得当前的状态信息
		String allStatus = getStatus(req, optStatus);
		try{
			GdtAdgroup adg = gdtAdgroupMapper.selectById(unitId);
			if (Objects.isNull(adg)) {
				return R.failed("无此广点通广告计划");
			}
			if(StringUtils.equals(allStatus,adg.getConfiguredStatus())){
				return R.failed("当前传入状态错误");
			}

			Map<String, String> map = gdtAccesstokenService.fetchAccesstoken(advertiserId.toString());
			if (null == map || StringUtils.isEmpty(map.get("access_token"))) {
				return R.failed("广点通账户授权失败，请重试！");
			}
			String urlstr = gdtUrl + gdtGroupUpdateUrl + "?" + MapUtils.queryString(map);
			Map<String, Object> params = new HashMap<>();
			params.put("account_id", advertiserId.toString());
			params.put("adgroup_id", unitId);
			params.put("configured_status", allStatus);
			//提交请求广点通修改广告组接口
			String resultStr = OEHttpUtils.doPost(urlstr, params);
			ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
			String adgId = null;
			if (StringUtils.equals(resBean.getCode(), "0")) {
				//同步修改数据库
				JSONObject jsonObj = resBean.getData();
				adgId = jsonObj.getString("adgroup_id");

				if (StringUtils.isBlank(adgId)) {
					return R.failed("获取广点通广告组id失败");
				}
				if (!adgId.equals(unitId.toString())) {
					return R.failed("投放平台与广点通广告组id不匹配");
				}
				GdtAdgroupDto adgroup=new GdtAdgroupDto();
				adgroup.setAdgroupId(unitId);
				adgroup.setConfiguredStatus(allStatus);
				int i = gdtAdgroupMapper.update(adgroup);
				return R.ok(i, "广点通广告组开关修改成功");
			}else {
				return R.failed("更新广点通状态失败:" + resBean.getMessage());
			}
		}catch (Exception e){
			e.printStackTrace();
			return R.failed("广点通广告组开关修改异常，请稍后重试");
		}
	}

	/**
	 * 修改快手状态
	 * @param req
	 * @return
	 */
	private R updateKSStatus(KsPlanReq req) {

		//广告账号id
		Long advertiserId = req.getAdvertiserId();
		//广告账号id
		Long unitId = req.getUnitId();
		//当前状态
		String optStatus = req.getOptStatus().toString();
		//获得当前的状态信息
		String allStatus = getStatus(req, optStatus);
		try {
			AccountToken ksAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.KS.getValue(),req.getAdvertiserId().toString());
			if (Objects.isNull(ksAccountToken)){
			return R.failed("此广告账户Token已失效");
			}
			DyKsClient ksClient = new DyKsClient("");
			KsUnit ksUnit = this.baseMapper.selectKsUnitList(unitId.toString());
			if (Objects.isNull(ksUnit)) {
				return R.failed("无此快手广告计划");
			}
			if(StringUtils.equals(allStatus,ksUnit.getPutStatus().toString())){
				return R.failed("当前传入状态错误");
			}

			KsUpdateStatusRequest updateStatusRequest = new KsUpdateStatusRequest();
			updateStatusRequest.setAdvertiser_id(advertiserId);
			updateStatusRequest.setUnit_id(unitId);
			updateStatusRequest.setPut_status(Integer.valueOf(allStatus));
			String result  = ksClient.call4Post(updateStatusRequest, ksAccountToken.getAccessToken());

			KsResponse response = JSON.parseObject(result, KsResponse.class);
			if ("0".equals(response.getCode())){
				KsUnit updateKsUnit=new KsUnit();
				updateKsUnit.setUnitId(req.getUnitId());
				updateKsUnit.setPutStatus(Integer.valueOf(allStatus));
				//修改数据表:ks_unit的出价信息
				this.baseMapper.update(updateKsUnit);
				return R.ok(response.getMessage(),">>>>>>更新快手状态成功");
			}else {
				log.error(">>>>>>更新快手状态失败："+ result);
				return R.failed(response.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("更新状态异常，请稍后重试");
		}

	}


	/**
	 * 修改快手状态
	 * @param req
	 * @return
	 */
	private R updateBdStatus(KsPlanReq req) {

		//广告账号id
		Long unitId = req.getUnitId();
		//当前状态
		String optStatus = req.getOptStatus().toString();
		ApiRequestHeader header = new ApiRequestHeader();
		try {
			AccountToken bdAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.BD.getValue(),req.getAdvertiserId().toString());
			if (Objects.isNull(bdAccountToken)){
				return R.failed("百度此广告账户Token已失效");
			}
			BdAdgroup bdAdgroup = bdAdgroupMapper.selectOne(Wrappers.<BdAdgroup>query().lambda()
					.eq(BdAdgroup::getDeleted, 0)
					.eq(BdAdgroup::getAdgroupFeedId, unitId));
			if (Objects.isNull(bdAdgroup)) {
				return R.failed("无此百度广告计划");
			}
			if(StringUtils.equals(optStatus,bdAdgroup.getPause().toString())){
				return R.failed("当前传入状态错误");
			}

			AdgroupFeedService adgroupFeedService = new AdgroupFeedService();
			UpdateAdgroupFeedRequestWrapper wrapper = new UpdateAdgroupFeedRequestWrapper();
			header.setAccessToken(bdAccountToken.getAccessToken());
			//注意这里传用户名，不是用户ID
			header.setUserName(bdAccountToken.getAdvertiserName());
			wrapper.setHeader(header);
			UpdateAdgroupFeedRequestWrapperBody body = new UpdateAdgroupFeedRequestWrapperBody();
			List<AdgroupFeedType> list = new ArrayList<>();
			AdgroupFeedType updateAdGroup = new AdgroupFeedType();
			list.add(updateAdGroup.adgroupFeedId(unitId).pause(optStatus.equals("1")));
			bdAdgroup.setPause(Integer.valueOf(optStatus));
			body.setAdgroupFeedTypes(list);
			wrapper.body(body);
			UpdateAdgroupFeedResponseWrapper responseWrapper = adgroupFeedService.updateAdgroupFeed(wrapper);
			if (StringUtils.equals(responseWrapper.getHeader().getDesc(), "success")) {
				//修改数据表:更新出价信息
				bdAdgroupMapper.updateById(bdAdgroup);
				return R.ok(">>>>>>百度修改广告计划状态成功");
			} else {
				List<String> mg = responseWrapper.getHeader().getFailures().stream().map(ApiErrorInfo::getMessage).collect(Collectors.toList());
				log.error(">>>>>>百度修改广告计划状态异常：" + JSON.toJSONString(responseWrapper));
				return R.failed(JSON.toJSONString(mg));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("更新状态异常，请稍后重试");
		}

	}

	private String getStatus(KsPlanReq req,String optStatus){
		String status=null;
		//1:开启   0:关闭
		if(StringUtils.equals(optStatus,"1")){
			//媒体类型 1.头条,8.广点通,10快手
			if(1==req.getMediaType()){
				if(req.getVersionType().equals("2")) {
					status = AdPlanEnum.TT_AD_STATUS_ENABLE_NEW.getType();
				}else {
					status = AdPlanEnum.TT_AD_STATUS_ENABLE.getType();
				}
			}else if(8==req.getMediaType()){
				status = AdPlanEnum.GDT_AD_STATUS_NORMAL.getType();
			}else if(10==req.getMediaType()){
				status = AdPlanEnum.KS_AD_STATUS_ENABLE.getType();
			}
		}else if(StringUtils.equals(optStatus,"0")){
			//媒体类型 1.头条,8.广点通,10快手
			if(1==req.getMediaType()){
				if(req.getVersionType().equals("2")) {
					status = AdPlanEnum.TT_AD_STATUS_DISABLE_NEW.getType();
				}else {
					status = AdPlanEnum.TT_AD_STATUS_DISABLE.getType();
				}
			}else if(8==req.getMediaType()){
				status = AdPlanEnum.GDT_AD_STATUS_SUSPEND.getType();
			}else if(10==req.getMediaType()){
				status = AdPlanEnum.KS_AD_STATUS_DISABLE.getType();
			}
		}
		return status;

	}

	/**
	 * @zhuxm
	 * @获取广告组账号预警阈值
	 */
	@SysLog("提交头条推广计划预警阈值")
	public R submitWarning(@Valid AdvertisingWarningVO vo) {

		if (vo == null) {
			return R.failed("参数不能为空");
		}
		if (StringUtils.isBlank(vo.getAdvertiserId())) {
			return R.failed("广告账号不允许为空");
		}
		TtPlanCostWarning entity = new TtPlanCostWarning();
		entity.setPlanCostWarning(vo.getPlanCostWarning());
		entity.setAdvertiserId(vo.getAdvertiserId());
		return R.ok(ttPlanCostWarningService.saveOrUpdate(entity));
	}

	/**
	 * @zhuxm
	 * @获取广告组账号预警阈值
	 */
	@SysLog("提交广告组账号预警阈值")
	public R submitWarning(@Valid GdtAdvFundsVO vo) {

		if (vo == null) {
			return R.failed("参数不能为空");
		}

		if (StringUtils.isBlank(vo.getAccountId())) {
			return R.failed("广告账号不允许为空");
		}

		UpdateWrapper<GdtAdvFunds> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("account_id", vo.getAccountId());
		updateWrapper.set("group_cost_warning", vo.getGroupCostWarning());

		return R.ok(gdtAdvFundsService.update(null, updateWrapper));
	}

}
